﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MapGIS.GeoDataBase;
using MapGIS.GeoDataBase.Convert;
using MapGIS.GeoObjects;
using MapGIS.GeoObjects.SpatialRef;
using System.IO;

namespace Wcf_MapFrame
{
    class InputShp
    {
        public static string Shp2Json(string url)
        {
            if (string.IsNullOrEmpty(url) || !File.Exists(url) || string.Compare(Path.GetExtension(url), ".shp", true) != 0)
                return "";
            string strRt = "";
            DataConvert DataCvr = new DataConvert();
            if (DataCvr.OpenSource(url) <= 0)
                return "";
            DataBase tempGDB = DataBase.OpenTempDB();
            SFeatureCls SFCls = tempGDB.GetXClass(XClsType.SFCls) as SFeatureCls;
            if (SFCls == null)
                goto end;
            FeatureInfo info = new FeatureInfo();
            DataCvr.GetSourceInfo(SourceInfoType.FEATURE_INFO, info);
            GeomType geoType = info.geoType;
            string clsName = Guid.NewGuid().ToString();
            if (SFCls.Create(clsName, geoType, 0, 0, null) <= 0)
                goto end;
            DataCvr.OpenDestination(SFCls);
            DataCvr.Convert();
            SRefData refData = tempGDB.SpatialRefMng.Get(SFCls.SrID);
            string epsg = "";
            if (refData != null)
                epsg = MapFrame.TransSRSNameByXml(refData.SRSName, false);
            //将要素类转为json
            strRt += "{ \"type\": \"FeatureCollection\",";
            strRt += TranGeoJson.TransSRS(epsg);
            strRt += ",\"features\": [";
            strRt += MapFrame.TransCls2GeoJson(SFCls);
            if (strRt[strRt.Length - 1] == ',')
                strRt = strRt.Substring(0, strRt.Length - 1);
            strRt += "]}";
        end:
            DataCvr.Close();
            if (SFCls == null)
                SFCls.Close();
            DataBase.FreeTempDB(tempGDB);
            return strRt;
        }
    }
}
